// 获取元素
let tbody = document.querySelector('tbody')

// =========================渲染===========================
function init() {
    axios({
        url: '/score/list'
    }).then(function (res) {
        // 得到的是对象
        let data = res.data.data
        let htmlStr = ''
        // 遍历对象
        for (const key in data) {
            htmlStr += ` <tr data-id="${key}">
                            <th scope="row">${key}</th>
                            <td>${data[key].name}</td>
                            <td class="score" data-batch="1">${data[key].score[0]}</td>
                            <td class="score" data-batch="2">${data[key].score[1]}</td>
                            <td class="score" data-batch="3">${data[key].score[2]}</td>
                            <td class="score" data-batch="4">${data[key].score[3]}</td>
                            <td class="score" data-batch="5">${data[key].score[4]}</td>
                        </tr>`
        }
        tbody.innerHTML = htmlStr
    })
}
init()
// ======================编辑和新增=========================
tbody.addEventListener('click', function (e) {
    if (e.target.className == 'score') {
        // e.target是点击的元素
        let td = e.target
        // 把值存起来
        let scope = td.innerText
        td.innerText = ''
        // 创建一个元素节点
        let myinput = document.createElement('input')
        // 追加一个类
        myinput.classList.add('youinput')
        // 追加到文本
        td.appendChild(myinput)
        // 获得焦点
        myinput.focus()
        myinput.value = scope

        // 失去焦点还原
        myinput.addEventListener('blur', function () {
            td.innerHTML = scope
        })

        // 添加键盘事件
        myinput.addEventListener('keyup', function (e) {
            if (e.key == "Enter") {
                if (myinput.value == '') {
                    toastr.error('没有输入内容');
                    myinput.blur()
                    return
                }
                axios({
                    url: '/score/entry',
                    method: 'post',
                    data: {
                        stu_id: td.parentNode.dataset.id,
                        batch: td.dataset.batch,
                        score: myinput.value
                    }
                }).then(function (res) {
                    toastr.success('录入或修改学员成绩成功')
                    let s = myinput.value
                    td.innerText = ''
                    td.innerHTML = s

                })
            }
        })
    }
})
